#region

using System;
using System.IO;

#endregion

namespace MediaController.Extractor
{
    public class PathUtils
    {
        public static bool Equals(DirectoryInfo a, DirectoryInfo b)
        {
            return ((a == b) ||
                    (((a != null) && (b != null)) &&
                     NormalizedDirectoryInfo(a).ToString().Equals(NormalizedDirectoryInfo(b).ToString())));
        }

        public static string FormatBytes(double bytes)
        {
            return FormatBytes((long)bytes);
        }

        public static string FormatBytes(long bytes)
        {
            string str;
            double num = bytes;
            var strArray = new[] { "B", "KB", "MB", "GB", "TB" };
            int index = 0;
            while (((num / 1024.0) > 1.0) && (index < strArray.Length))
            {
                num /= 1024.0;
                index++;
            }
            if (index == 0)
            {
                str = "{0:#0} {1:g}";
            }
            else
            {
                str = "{0:#0.00} {1:g}";
            }
            return string.Format(str, num, strArray[index]);
        }

        public static string GetDiskVolume(string p)
        {
            if (Directory.GetDirectoryRoot(p).Equals(p))
            {
                int length = p.LastIndexOf(Path.DirectorySeparatorChar);
                p = (length != -1) ? p.Substring(0, length) : p;
                foreach (var str in Directory.GetLogicalDrives())
                {
                    if (str.StartsWith(p, StringComparison.CurrentCultureIgnoreCase))
                    {
                        return p;
                    }
                }
                return null;
            }
            if (JunctionPoint.Exists(p))
            {
                p = JunctionPoint.GetTarget(p);
            }
            return GetDiskVolume(Path.GetDirectoryName(p));
        }

        public static DirectoryInfo NormalizedDirectoryInfo(DirectoryInfo d)
        {
            return new DirectoryInfo(NormalizePath(d.ToString()));
        }

        public static string NormalizePath(string p)
        {
            if (!Path.GetPathRoot(p).Equals(p))
            {
                while ((p != string.Empty) && (p[p.Length - 1] == Path.DirectorySeparatorChar))
                {
                    p = p.Substring(0, p.Length - 1);
                }
                return p;
            }
            return p;
        }
    }
}